package com.app.common.utils.tenCos;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.app.common.utils.http.HttpRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 腾讯临时COS工具类（对接 Node.js 文件服务）
 *
 * @author 徐朴芬
 */
@Component
public class TenCosUtils {

    private static String tenCosUrl;

    @Value("${TenCos.url}")
    public void setTenCosUrl(String url) {
        TenCosUtils.tenCosUrl = url;
    }

    /**
     * 获取 COS 文件列表
     */
    public static List<JSONObject> listTenCos() throws IOException {
        List<JSONObject> list = new ArrayList<>();
        String res = HttpRequest.get(tenCosUrl + "/list", null, null);

        JSONObject obj = JSONObject.parseObject(res);
        if (obj == null || !"200".equals(String.valueOf(obj.get("code")))) {
            throw new IOException("获取列表失败：" + res);
        }

        JSONArray data = obj.getJSONArray("data");
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                list.add(data.getJSONObject(i));
            }
        }
        return list;
    }

    /**
     * 上传文件到 COS
     *
     * @param file 文件对象
     * @return 文件路径（绝对路径）
     */
    public static String uploadTenCos(File file) throws IOException {
        if (file == null || !file.exists()) {
            throw new IOException("文件不存在");
        }

        String res = HttpRequest.uploadFile(tenCosUrl + "/upload", file, null, null);
        JSONObject obj = JSONObject.parseObject(res);

        if (obj == null || !"200".equals(String.valueOf(obj.get("code")))) {
            throw new IOException("上传失败：" + res);
        }

        JSONObject data = obj.getJSONObject("data");
        return data.getString("name");
    }

    /**
     * 删除 COS 文件
     */
    public static boolean deleteTenCos(String fileName) throws IOException {
        JSONObject body = new JSONObject();
        body.put("fileName", fileName);

        String res = HttpRequest.postJson(tenCosUrl + "/delete", body.toJSONString(), null);
        JSONObject obj = JSONObject.parseObject(res);

        return obj != null && "200".equals(String.valueOf(obj.get("code")));
    }
}
